function [newpath,ch] = ch_exdir( rpath , varargin ); 
% ======================================================================
% CH_EXDIR
%
% Check that the directory formed by combining several possible inputs
% exists and provide the appropriate string for that path 
% 
% RPATH     Root path from where to start looking 
%           If [] will be where the invoking code is running from 
% 
% VARARGIN  Variable number of strings to be combined to form a final
%           directory name 
% 
% In the case of UNIX the code will check if an all upper or lower caps of
% the directory exists, if the original desired path does not exist 
% 
% NEWPATH   Corresponding string 
% CH        ==0 if the path does not exist, different from zero otherwise 
% 
% Use CR_DIR.m to create composite directory names without checking
% existence 
% 
% Alejandro Justiniano 10/20/2005 
% =========================================================================
cucd = cd; 
nn = nargin; 
if nn == 1 
    error('Need at least 1 input other than the rootpath') 
end 
if isempty( rpath ) 
    rpath = cd ; 
end 
ind = isunix; 
if ind== 1  
    sep = '/'; 
else 
    sep = '\'; 
end 
   
newpath =rpath; 
ii=1; 
for ii=1:nn-1;
    
    temp = [newpath,sep,varargin{ii}]; 

    cd(newpath)
    ch = exist( varargin{ii}, 'dir' ); 
    if ch == 0
        if ind == 1
            ch_one = exist( lower( varargin{ii} ), 'dir' );
            cd(cucd);
            if ch_one ~= 0
                disp( [ 'Warning : ',temp ,' exists only in ALL LOWERCASE' ])
            else
                ch_two = exist( upper( varargin{ii} ) , 'dir') ;
                if ch_two ~= 0
                    disp([ 'Warning : ',temp ,' exists only in ALL UPPERCASE' ])
                else
                    disp([ 'UNIX directory ',temp ,' does not exist ']); 
                    error( [ 'UNIX directory ',temp ,' does not exist '] ); 
                end
            end
        else
            disp([ 'WINDOWS directory: ',temp ,' does not exist' ]); 
            error( [ 'UNIX directory ',temp ,' does not exist '] );
        end
        return; 
    end 
    cd(cucd); 
    newpath = temp ; 
end 